package com.sky.service.impl;

import com.sky.entity.Orders;
import com.sky.entity.User;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceServiceImpl workspaceService;

    @Override
    public TurnoverReportVO getTurnover(LocalDate beginTime, LocalDate endTime) {
        List<LocalDate> localDates = new ArrayList<>();
        localDates.add(beginTime);
        while (!beginTime.equals(endTime)) {
            beginTime = beginTime.plusDays(1);
            localDates.add(beginTime);
        }
        List<Double> sumAmountsList = new ArrayList<>();
        for (LocalDate localDate : localDates) {
            LocalDateTime  begin=LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime  end=LocalDateTime.of(localDate, LocalTime.MAX);
            Double sumAmounts= orderMapper.sumAmount(begin,end,Orders.COMPLETED);
            if (sumAmounts==null){
                sumAmounts=0.0;
            }
            log.info("营业额是：{}",sumAmounts);
            sumAmountsList.add(sumAmounts);
        }
        return TurnoverReportVO
                .builder()
                .dateList(localDates.toString())
                .turnoverList(sumAmountsList.toString())
                .build();
    }

    @Override
    public UserReportVO getUser(LocalDate beginTime, LocalDate endTime) {
        List<LocalDate> localDates = new ArrayList<>();
        localDates.add(beginTime);
        while (!beginTime.equals(endTime)) {
            beginTime = beginTime.plusDays(1);
            localDates.add(beginTime);
        }
        List<Integer> newUserList=new ArrayList<>();
        List<Integer> totalUserList=new ArrayList<>();
        for (LocalDate localDate : localDates) {
            LocalDateTime  begin=LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime  end=LocalDateTime.of(localDate, LocalTime.MAX);
            Integer newUserListnumber=userMapper.selectByCreateTime(begin,end);
            newUserList.add(newUserListnumber);
            Integer totalUserListnumber =userMapper.select();
            totalUserList.add(totalUserListnumber);
        }

        return UserReportVO
                .builder()
                .dateList(localDates.toString())
                .newUserList(newUserList.toString())
                .totalUserList(totalUserList.toString())
                .build();
    }

    @Override
    public OrderReportVO getOrderReport(LocalDate beginTime, LocalDate endTime) {

        List<LocalDate> localDates = new ArrayList<>();
        localDates.add(beginTime);
        while (!beginTime.equals(endTime)) {
            beginTime = beginTime.plusDays(1);
            localDates.add(beginTime);
        }
        List<Integer> orderCountList=new ArrayList<>();
        List<Integer> validOrderCountList=new ArrayList<>();
        for (LocalDate localDate : localDates) {
            LocalDateTime  begin=LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime  end=LocalDateTime.of(localDate, LocalTime.MAX);
            Integer orderCount=orderMapper.selectCount(begin,end);
            orderCountList.add(orderCount);
            Integer validOrderCount=orderMapper.selectvalidCount(begin,end,Orders.COMPLETED);
            validOrderCountList.add(validOrderCount);
        }
        Integer totalOrderCount=orderMapper.selectCountAll();
        Integer validOrderCount=orderMapper.selectvalidCountAll(Orders.COMPLETED);
        Double orderCompletionRate=Double.valueOf(validOrderCount)/Double.valueOf(totalOrderCount);

        return OrderReportVO
                .builder()
                .dateList(localDates.toString())
                .orderCountList(orderCountList.toString())
                .validOrderCountList(validOrderCountList.toString())
                .orderCompletionRate(orderCompletionRate)
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .build();
    }

    @Override
    public SalesTop10ReportVO top10Statistics(LocalDate beginTime, LocalDate endTime) {
        List<String> nameList=new ArrayList<>();
        List<Integer> numberList=new ArrayList<>();
        List<Top10> top10List=orderMapper.selectTop10(beginTime,endTime);
        log.info("---------------------top10List:{}",top10List);
        for (Top10 top10 : top10List) {
              nameList.add(top10.getName());
              numberList.add(top10.getNum());
        }

        return SalesTop10ReportVO
                .builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }


    /**
     * 导出Excel表
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {


        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        log.info("==================开始日期===================：{}",begin);
        log.info("==================开始日期===================：{}",end);
        //查询概览运营数据，提供给Excel模板文件
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin,LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //基于提供好的模板文件创建一个新的Excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            //获得Excel文件中的一个Sheet
            XSSFSheet sheet = excel.getSheet("Sheet1");

            sheet.getRow(1).getCell(1).setCellValue(begin + "至" + end);
            //获得第4行
            XSSFRow row = sheet.getRow(3);
            //获取单元格
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                //准备明细数据
                businessData = workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }
            //通过输出流将文件下载到客户端浏览器中
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            //关闭资源
            out.flush();
            out.close();
            excel.close();

        }catch (IOException e){
            e.printStackTrace();
        }

    }

}
